﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommonTools;
using NS_Log;

namespace Common
{
    //数据报类
    public class Datagram
    {
        public int isVaild { get; set; }//是否为有效的数据包(0正常，>0错误码）
        public byte[] fullPack { get; set; }//一个完整的包字节数组

        public int serialNo { get; set; }//指令码
        public int cmdCode { get; set; }//指令码
        public byte[] content { get; set; }//内容

        public Datagram() 
        {
        
        }

        /// <summary>
        /// 生成数据包
        /// </summary>
        /// <param name="serial">流水号</param>
        /// <param name="icode">命令码</param>
        /// <param name="device">设备编码</param>
        /// <param name="msg">数据内容</param>
        public Datagram(int serial,int icode, string device, byte[] msg) 
        {

        }
        /// <summary>
        /// 解析接收到的一个数据包
        /// </summary>
        /// <param name="onePack">一个包字节</param>
        public Datagram(byte[] onePack)
        {
            try
            {
                fullPack = new byte[onePack.Length];
                onePack.CopyTo(fullPack,0);

                serialNo = onePack[5] * 0x100 + onePack[4];
                cmdCode = onePack[6] * 0x100 + onePack[7];
                int len=onePack[3] * 0x100 + onePack[2];
                len = len -7;
                content = onePack.Skip(8).Take(len).ToArray();
                isVaild = 0;
            }
            catch (Exception ex)
            {
                MyLog.Instance.log("Datagram Exception:" + ex.StackTrace);
                isVaild = 100;
            }
        }

        /// <summary>
        /// 生成应答命令
        /// </summary>
        /// 返回去的错误码
        /// <returns></returns>
        public byte[] getAckCode(byte errorNo)
        {
            byte[] ackPack = new byte[12];
            
            //包头FAFB
            ackPack[0] = 0xFA;
            ackPack[1] = 0xFB;
            //包长度
            ackPack[2] = 8;
            ackPack[3] = 0;
            //流水号
            ackPack[4] = fullPack[5];
            ackPack[5] = fullPack[6];
            //命令码
            ackPack[6] = fullPack[7];
            ackPack[7] = (byte)(fullPack[8]+1);
            //错误码
            ackPack[8] = errorNo;
            //校验码
            ackPack[9] = 0xFF;
            //包尾FCFD
            ackPack[10] = 0xFC;
            ackPack[11] = 0xFD;

            return ackPack;
        }
        /// <summary>
        /// 获取信息内容
        /// </summary>
        /// <returns></returns>
        public string getCtn()
        {
            return"";
        }
    }
}
